<?php
/*
Hack Name: Wordpress Theme Toolkit
Plugin URI: http://frenchfragfactory.net/ozh/my-projects/wordpress-theme-toolkit-admin-menu/
Description: Helps theme authors set up an admin menu. Helps theme users customise the theme.
Version: 1.12
Author: Ozh
Author URI: http://planetOzh.com/
*/

/************************************************************************************
*							 DO NOT MODIFY THIS FILE !
************************************************************************************/

/* RELEASE HISTORY :
* 1.0 : initial release
* 1.1 : update for Wordpress 2.0 compatibility
* 1.11 : added {separator} template
* 1.12 : more or less minor bug fixing (one when no plugin activated, other with rare mod_security issue) and better compliancy with WP 2.0 roles
*/

if (!function_exists('themetoolkit')) {
	function themetoolkit($theme='',$array='',$file='') {
		global ${$theme};
		if ($theme == '' or $array == '' or $file == '') {
			die ('No theme name, theme option, or parent defined in Theme Toolkit');
		}
		${$theme} = new ThemeToolkit($theme,$array,$file);
	}
}

if (!class_exists('ThemeToolkit')) {
	class ThemeToolkit{

		var $option, $infos;

		function ThemeToolkit($theme,$array,$file){
			
			if ( count(@preg_grep('#^\.\./themes/[^/]+/functions.php$#', get_settings('active_plugins'))) > 0 ) {
				wp_cache_flush();
				$this->upgrade_toolkit();
			}
			
			$this->infos['path'] = '../themes/' . basename(dirname($file));

			/* Create some vars needed if an admin menu is to be printed */
			if ($array['debug']) {
				if ((basename($file)) == $_GET['page']) $this->infos['debug'] = 1;
				unset($array['debug']);
			}
			if ((basename($file)) == $_GET['page']){
				$this->infos['menu_options'] = $array;
				$this->infos['classname'] = $theme;
			}
			$this->option=array();

			/* Get infos about the theme and particularly its 'shortname'
			 * which is used to name the entry in wp_options where data are stored */
			$this->do_init();

			/* Read data from options table */
			$this->read_options();

			/* Are we in the admin area ? Add a menu then ! */
			$this->file = $file;
			add_action('admin_menu', array(&$this, 'add_menu'));
		}


		/* Add an entry to the admin menu area */
		function add_menu() {
			global $wp_version;
			if ( $wp_version >= 2 ) {
				$level = 'edit_themes';
			} else {
				$level = 9;
			}
			//add_submenu_page('themes.php', 'Configure ' . $this->infos[theme_name], $this->infos[theme_name], 9, $this->infos['path'] . '/functions.php', array(&$this,'admin_menu'));
			add_theme_page(__('Configure', simpax).' '. $this->infos['theme_name'].'-'.__('Optionen','simpax').'', $this->infos['theme_name'].'-'.__('Optionen','simpax').'', 'edit_themes', basename($this->file), array(&$this,'admin_menu'));
			/* Thank you MCincubus for opening my eyes on the last parameter :) */
		}

		/* Get infos about this theme */
		function do_init() {
			$themes = get_themes();
			$shouldbe= basename($this->infos['path']);
			foreach ($themes as $theme) {
				$current= basename($theme['Template Dir']);
				if ($current == $shouldbe) {
					if (get_settings('template') == $current) {
						$this->infos['active'] = TRUE;
					} else {
						$this->infos['active'] = FALSE;
					}
				$this->infos['theme_name'] = $theme['Name'];
				$this->infos['theme_shortname'] = $current;
				$this->infos['theme_site'] = $theme['Title'];
				$this->infos['theme_version'] = $theme['Version'];
				$this->infos['theme_author'] = preg_replace("#>\s*([^<]*)</a>#", ">\\1</a>", $theme['Author']);
				}
			}
		}

		/* Read theme options as defined by user and populate the array $this->option */
		function read_options() {
			$options = get_option('theme-'.$this->infos['theme_shortname'].'-options');
			$options['_________junk-entry________'] = 'ozh is my god';
			foreach ($options as $key=>$val) {
				$this->option["$key"] = stripslashes($val);
			}
			array_pop($this->option);
			return $this->option;
			/* Curious about this "junk-entry" ? :) A few explanations then.
			 * The problem is that get_option always return an array, even if
			 * no settings has been previously saved in table wp_options. This
			 * junk entry is here to populate the array with at least one value,
			 * removed afterwards, so that the foreach loop doesn't go moo. */
		}

		/* Write theme options as defined by user in database */
		function store_options($array) {
			update_option('theme-'.$this->infos['theme_shortname'].'-options','');
			if (update_option('theme-'.$this->infos['theme_shortname'].'-options',$array)) {
				return __('Optionen gespeichert','simpax');
			} else {
				return __('Konnte Optionen nicht speichern!!','simpax');
			}
		}

		/* Delete options from database */
		  function delete_options() {
			/* Remove entry from database */
			delete_option('theme-'.$this->infos['theme_shortname'].'-options');
			/* Unregister this file as a plugin (therefore remove the admin menu) */
			$this->depluginification();
			/* Revert theme back to Kubrick if this theme was activated */
			if ($this->infos['active']) {
				update_option('template', 'default');
				update_option('stylesheet', 'default');
				do_action('switch_theme', 'Default');
			}
			/* Go back to Theme admin */
			print '<meta http-equiv="refresh" content="0;URL=themes.php?activated=true">';
			echo "<script> self.location(\"themes.php?activated=true\");</script>";
			exit;
		}

		/* Check if the theme has been loaded at least once (so that this file has been registered as a plugin) */
		function is_installed() {
			global $wpdb;
			$where = 'theme-'.$this->infos['theme_shortname'].'-options';
			$check = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->options WHERE option_name = '$where'");
			if ($check == 0) {
				return FALSE;
			} else {
				return TRUE;
			}
		}

		/* Theme used for the first time (create blank entry in database) */
		function do_firstinit() {
			global $wpdb;
			$options = array();
			foreach(array_keys($this->option) as $key) {
				$options["$key"]='';
			}
			add_option('theme-'.$this->infos['theme_shortname'].'-options',$options, 'Options for theme '.$this->infos['theme_name']);
			return "".__('Standart Theme Optionen zur Datenbank hinzugef&uuml;gt (1 Eintrag in der Tabelle', simpax)." '". $wpdb->options ."')";
		}

		/* The mother of them all : the Admin Menu printing func */
		function admin_menu () {
			global $cache_settings, $wpdb;

			/* Process things when things are to be processed */
			if (@$_POST['action'] == 'store_option') {
				unset($_POST['action']);
				$msg = $this->store_options($_POST);
			} elseif (@$_POST['action'] == 'delete_options') {
				$this->delete_options();
			} elseif (!$this->is_installed()) {
				$msg = $this->do_firstinit();
			}

			if (@$msg) print "<div class='updated'><p><b>" . $msg . "</b></p></div>\n";
			
			echo '<link rel="stylesheet" href="'.get_bloginfo('stylesheet_directory').'/options/ap/ap.css" />';
			echo '<div class="wrap" style="background: url('.get_bloginfo('stylesheet_directory').'/img/logo-trans.png) right top no-repeat #fff;">';
		
			if (!$this->infos['active']) { /* theme is not active */
				echo '<p>'.__('(Bitte beachte, dass dieses theme momentan <strong>nicht aktiviert</strong> ist!)', simpax).'</p>';
			}

			$cache_settings = '';
			$check = $this->read_options();
			$ct = current_theme_info();
		
			echo '<h2>' . $this->infos['theme_site'] . ' '.__('Optionen','simpax').'</h2>';
			echo "<div id='caxtop'><span style='float: left; padding-right: 30px; padding-left: 20px;'><br /><iframe width='165' scrolling='no' height='100' frameborder='0' src='http://testkc.te.funpic.de/wp-content/themes/cax/version_check/version-check-server.php?version={$ct->version} '></iframe></span>";
     		echo '<p><br/><br/>'.__('<strong>Danke, dass du '.$this->infos['theme_site'].' installiert hast</strong>, ein sch&ouml;nes und umfangreiches Theme f&uuml;r WordPress. Mehr Informationen &uuml;ber '.$this->infos['theme_site'].' findest du im <a href="http://code.google.com/p/cax/w/list">Wiki</a>. wenn du Fragen hast, wennde dich an unsere <a href="http://groups.google.com/group/gcax">Google Group</a>!
		','simpax').'</p>';
			
		/* caxDevBlog RSS */
		if(file_exists(ABSPATH . WPINC . '/rss.php')) :
			require_once (ABSPATH . WPINC . '/rss.php');
			$rss_cax = @fetch_rss('http://feeds.feedburner.com/caxdevblog');	
			if ( isset($rss_cax->items) && 0 != count($rss_cax->items) ) {
			echo "<p><strong>Neues im caxDevBlog:</strong> ";
			$rss_cax->items = array_slice($rss_cax->items, 0, 3);
			foreach ($rss_cax->items as $item ) {			
				$item_number++;
				echo "<a href=\"" . wp_filter_kses($item['link']) . "\">" . wptexturize(wp_specialchars($item['title'])) . "</a> &#183; ";
			}
			echo "<a href=\"http://cax-theme.info/blog/\">Mehr</a></p>";
			}
		endif;
		
			echo '<div id="the_cax_options">';
			echo '<br clear="both" /><form action="" method="post">
			<input type="hidden" name="action" value="store_option">';



			/* Print form, here comes the fun part :) */
			foreach ($this->infos['menu_options'] as $key=>$val) {
				$items='';
				preg_match('/\s*([^{#]*)\s*({([^}]*)})*\s*([#]*\s*(.*))/', $val, $matches);
				if ($matches[3]) {
					$items = split("\|", $matches[3]);
				}

				if (@$items) {
					$type = array_shift($items);
					switch ($type) {
					case 'separator':
						print ''.$matches[1].'';
						break;
					case 'radio':
						print '<br style="clear: both;" /><div class="cax_title">'.$matches[1]."</div>";
						print '<div class="cax_radio">';
						print '<ul class="cax_ul_radio">';
						while ($items) {
							$v=array_shift($items);
							$t=array_shift($items);
							$checked='';
							if ($v == $this->option[$key]) $checked='checked';
							print "<li><label for='${key}${v}'><input class='cax_radiobutton' type='radio' id='${key}${v}' name='$key' value='$v' $checked /> $t</label></li>";
							if (@$items) print "\n";
							else print '</ul><br style="clear: both;" /></div>';
						}
						break;
						print '</div>';
					case 'textarea':
						$rows=array_shift($items);
						$cols=array_shift($items);
					print "<label for='$key'><div class='cax_title'>".$matches[1]."</div></label>";
						print "<div class='cax_text'><textarea name='$key' id='$key' rows='$rows' cols='$cols'>" . $this->option[$key] . "</textarea></div>";
						break;
					case 'checkbox':
						print '<br style="clear: both;" /><div class="cax_title">'.$matches[1]."</div>";
						print '<div class="cax_checkbox">';
						print '<ul class="cax_ul_checkbox">';
						while ($items) {
							$k=array_shift($items);
							$v=array_shift($items);
							$t=array_shift($items);
							$checked='';
							if ($v == $this->option[$k]) $checked='checked';
							print "<li><label for='${k}${v}'><input class='cax_checkboxbutton' type='checkbox' id='${k}${v}' name='$k' value='$v' $checked /> $t</label></li>";
							if (@$items) print "\n";
							else print '</ul></div>';
						}
						break;
						print '</div></div>';
					}
				} else {
					print "<br style='clear: both;' /><label for='$key'><div class='cax_title'>".$matches[1]."</div></label>";
					print "<input class='cax_input' type='text' name='$key' id='$key' value='" . $this->option[$key] . "' />";
				}

				if ($matches[5]) print '<div class="cax_description">'. $matches[5].'</div><br style="clear: both;" />';
			}
			echo '</div>
			<p class="submit" id="cax_saveoptions">
				<a id="cax_scrolltop" href="#" title="nach oben scrollen">^</a>
				<input type="submit" accesskey="s" value="'. __('Optionen speichern','simpax').'" />
			</p>
			
			</form>';

			if ($this->infos['debug'] and $this->option) {
				$g = '<span style="color:#006600">';
				$b = '<span style="color:#0000CC">';
				$o = '<span style="color:#FF9900">';
				$r = '<span style="color:#CC0000">';
				echo '<h2>'.__('Entwickler-Ecke', simpax).'</h2>';
				echo '<p>'.__('Der array ','simpax').'<em>$'. $this->infos['classname'] . '->option</em> '.__('hat momentan folgende Schl&uuml;ssel und Werte:','simpax').'</p>
				<p><pre class="updated">';
				$count = 0;
				foreach ($this->option as $key=>$val) {
					$val=str_replace('<','&lt;',$val);
					if ($val) {
						print '<span class="ttkline">'.$g.'$'.$this->infos['classname'].'</span>'.$b.'-></span>'.$g.'option</span>'.$b.'[</span>'.$g.'\'</span>'.$r.$key.'</span>'.$g.'\'</span>'.$b.']</span>'.$g.' = "</span>'. $o.$val.'</span>'.$g."\"</span></span>\n";
						$count++;
					}
				}
				if (!$count) print "\n\n";
				echo '</pre><p>'.__('Um diese Ausgabe zu deaktivieren (z.B. wenn Du das Theme ver&ouml;ffentlichen willst), musst Du die Zeile "&nbsp;<em>\'debug\' => \'debug\'</em>&nbsp;" in der <em>functions.php</em> entfernen.','simpax').'</p>';
			}
			
		echo '<br/><br/><h2>'.__('Theme Optionen l&ouml;schen','simpax').'</h2>';
      
			echo '<p>'.__('Um die Theme Einstellungen vollst&auml;ndig zu entfernen (Erinnerung: Sie liegen alle in einem Eintrag in der Optionen Tabelle von Wordpress), klicke einfach auf den folgenden Button. Du wirst dann zur <a href="themes.php">Theme-&Uuml;bersicht</a> weitergeleitet!','simpax').'';
			
      if ($this->infos['active']) {
				echo __(' und das Standart-Theme wird aktiviert.','simpax').'';
			}
			echo '</p>
			<p>'.__('<strong>Hinweis f&uuml;r Blogs, wo die User das Theme wechseln k&ouml;nnen:</strong> (z.B. mit dem Theme Switcher Plugin)<br/>
			Auch wenn du die Datenbank-Eintr&auml;ge des Themes l&ouml;schst, wird sich das Theme mit den Standart-Einstellungen wieder eintragen, wenn ein User das Theme ausw&auml;hlt. Das kann zu b&ouml;sen &Uuml;berraschungen f&uuml;hren! Benutz den "L&ouml;schen"-Knopf also nur, wenn du dir absolut sicher bist!','simpax').'</p>
			<form action="" method="post">
			<input type="hidden" name="action" value="delete_options">
			<p class="submit" id="cax_delete_options"><input type="submit" value="'. __('Theme Optionen l&ouml;schen','simpax').'" onclick="return confirm(\''. __('Bist du dir wirklich sicher?','simpax').'\');"/></p>
			</form>';
			
			ob_start(array(&$this,'footercut'));

			echo '<h2>'.__('Credits','simpax').'</h2>';
			echo '<p>'.$this->infos['theme_site'].' '.__('ist von','simpax').' '.$this->infos['theme_author'].'. ';
			echo ''.__('Das Admin-men&uuml; benutzt das','simpax').' <a href="http://frenchfragfactory.net/ozh/my-projects/wordpress-theme-toolkit-admin-menu/" title="Wordpress Theme Toolkit : create a admin menu for your own theme as easily as editing 3 lines">Wordpress Theme Toolkit</a> '.__('von','simpax').' <a href="http://frenchfragfactory.net/ozh/" title="planetOzh">Ozh</a>. '.__('All das ist nat&uuml;rlich nur m&ouml;glich dank <a href="http://wordpress.org/" title="Best. Blogware. Ever.">Wordpress</a>. Besonderen dank auch an <a href="http://wordpress-deutschland.org/" title="WordPress Deutschland">WordPress Deutschland.</a>','simpax').'.</p>
			</div>';
			echo '</div><!-- footercut -->';
		}

		/* Make this footer part of the real #footer DIV of Wordpress admin area */
		function footercut($string) {
			return preg_replace('#</div><!-- footercut -->.*<div id="footer">#m', '', $string);
		}


		function upgrade_toolkit () {
			$plugins=get_settings('active_plugins');
			$delete=@preg_grep('#^\.\./themes/[^/]+/functions.php$#', $plugins);
			$result=array_diff($plugins,$delete);
			$temp = array();
			foreach($result as $item) $temp[]=$item;
			$result = $temp;
			update_option('active_plugins',$result);
			wp_cache_flush;
		}

	}
}

?>
